package com.ylsdxy.school_sys_set.controller;

import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;


@RestController
@RequestMapping("/oss")
public class OssController {
    @Resource
    OSSClient ossClient; //oss客户端

    @Value("${alibaba.bucket-name}") //获取yml的自定义桶名
    String bucketName;

    @Value("${alibaba.cloud.oss.endpoint}") //端点名
    private  String endpoint;

    @RequestMapping("upload")
    public String upload(MultipartFile file) throws IOException {
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件输入流
        InputStream inputStream = file.getInputStream();
        //设置对象
        ossClient.putObject(bucketName,fileName,inputStream);
        //设置文件的属性 例如过期时间
        Date date = new Date(new Date().getTime() + 60*24 * 60 * 60 * 1000);
        //上传文件
        URL url = ossClient.generatePresignedUrl(bucketName, fileName, date);

        //得到路径  完整路径  https://桶名.端点名/文件名
        return "https://"+bucketName+"."+endpoint+url.getPath();
    }


}
